package com.jinyi.wwdeng.ui.launch.impl

import android.content.Context
import com.hjq.permissions.XXPermissions
import com.jinyi.base.mvp.BasePresenter
import com.jinyi.wwdeng.AppConfigs
import com.jinyi.wwdeng.analysis.TestAnalysisInit
import com.jinyi.wwdeng.analysis.TestDataLibInit
import com.jinyi.wwdeng.ui.launch.contract.LaunchContract
import org.json.JSONObject

/**
 * JinYiTest
 *
 * @Author：wwdeng
 * @CreateTime：2024/4/26 18:45
 * <pre>
 * Presenter 实现类
</pre> *
 */
class LaunchPresenterImpl : BasePresenter<LaunchContract.View?, LaunchModelImpl?>(), LaunchContract.Presenter {

    override fun createModel(): LaunchModelImpl {
        return LaunchModelImpl(this)
    }

    /**
     * 获取转发地区 Timezone
     * @param params
     */
    fun loadTimezoneRequest( params: JSONObject?) {
        if (isViewDestory()) {
            return
        }
        mvpView!!.showLoading("")
        model!!.loadTimezoneRequest(params!!)
    }

    /**
     * APP 配置请求
     * @param params
     */
    fun loadAppInfoRequest(params: JSONObject?) {
        if (isViewDestory()) {
            return
        }
        model!!.loadAppInfoRequest(params!!)
    }

    /**
     * 转发地区成功回调
     * @param data
     */
    override fun onTimeZoneSuccess(data: JSONObject?) {
        if (isViewDestory()) {
            return
        }
        val code = data!!.optInt("code")
        when(code){
            0 -> {//成功
                val dataString = data.optString("data")
                val timeZone = dataString.split(",")[0]
                val zoneCode = dataString.split(",")[1]
                //保存转发地区
                AppConfigs.saveSPData(AppConfigs.SP_KEY.SP_HENECREDIT_TIMEZONE,timeZone)
                //保存转发地区 区号
                AppConfigs.saveSPData(AppConfigs.SP_KEY.SP_HENECREDIT_TIMEZONE_CODE,zoneCode)
                //初始化analysis lib 赋值 转发地区
                TestAnalysisInit.initAnalysisLibAtZoneSuccess()
                //初始化 data lib
                TestDataLibInit.initDataLibAtZoneSuccess()

                mvpView!!.showTimeZoneSuccess(timeZone)
            }
            else -> {//失败
                val msg = data.optString("msg")
                mvpView!!.showFailure(msg)
            }
        }
    }

    /**
     * APP 配置请求成功回调
     * @param data
     */
    override fun onAppInfoSuccess(data: JSONObject?) {
        if (isViewDestory()) {
            return
        }
        mvpView!!.hideLoading()
        val code = data!!.optInt("code")
        when(code){
            0 -> {//成功
                val obj = data.optJSONObject("obj")
                //保存所有数据
                if (obj != null) {
                    AppConfigs.saveSPData(AppConfigs.SP_KEY.SP_HENECREDIT_COMMON,obj.toString())
                }

                val customizeObj = obj?.optJSONObject("customize")
                val permissionsObj = customizeObj?.optJSONObject("permissions")
                val permissionArray = permissionsObj?.optJSONArray("permission")
//                val home = permissionsObj?.optJSONArray("home")
//                home!!.put("android.permission.CAMERA")
                if (permissionArray != null) {
                    if (permissionArray.length() > 0){
                        //是否全部申请
                        var isAll = true
                        for (i in 0..<permissionArray.length()){
                            val permission = permissionArray.optString(i)
                            //存在未授权的权限
                            if (!XXPermissions.isGranted(mvpView!!.getContext()!!, permission)){
                                isAll = false
                                break
                            }
                        }
                        if (isAll){//已全部授权

                            //已登录 - 进入主页
                            if (AppConfigs.getSPBoolean(AppConfigs.SP_KEY.SP_HENECREDIT_LOGIN)){
                                //初始化analysis lib 赋值 用户id 和 token
                                TestAnalysisInit.initAnalysisLibAtLoginSuccess()
                                mvpView!!.showMainAction()
                            } else {//进入登录页
                                mvpView!!.showLoginAction()
                            }

                        } else {
                            //进入权限页
                            mvpView!!.showPermissionAction(permissionArray.toString())
                        }
                    } else {
                        //进入登录
                        mvpView!!.showLoginAction()
                    }
                }
            }
            else -> {
                val msg = data.optString("msg")
                mvpView!!.showFailure(msg)
            }
        }
//        getMvpView()!!.showAppInfoSuccess(data)
    }

    /**
     * 接口请求失败
     * @param errorMsg
     */
    override fun onFailure(errorMsg: String?) {
        if (isViewDestory()) {
            return
        }
        mvpView!!.hideLoading()
        mvpView!!.showFailure(errorMsg)
    }

    override val context: Context?
        get() = if (!isViewDestory()) {
            mvpView!!.getContext()
        } else null
}
